package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;


/**
 * 08-响应对象之文件下载
 */
@WebServlet("/demo15")
public class Demo15Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //①获取下载文件的名称
        String fileName = request.getParameter("fileName");
        //②告诉浏览器必须打开一个下载窗口(Content-Disposition)
        //手动编码文件名称
        String newFileName = URLEncoder.encode(fileName,"utf-8");
        response.setHeader("Content-Disposition", "attachement;filename=" + newFileName);


        //③告诉浏览器下载文件的mimeType
        String mimeType = getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);
        //④IO拷贝
        //E:\workspace\220106\day05\out\artifacts\day05_war_exploded\download\girl1.jpg
        String downloadFilePath = getServletContext().getRealPath("/download/" + fileName);
        System.out.println("downloadFilePath = " + downloadFilePath);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadFilePath));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] bys = new byte[8192];
        int len = -1;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }
        //⑤释放资源
        bis.close();
        bos.close();//手动刷新最后的一次的缓冲区
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
